import fg from "fast-glob";
import path from "path";
import { toolchain } from "../toolchain.js";
import { UnityHelper } from "./UnityHelper.js";
import { Unity } from "../typings/unity.js";

export class TextFormatChecker {
    async check(): Promise<void> {
        const [target, format] = toolchain.opts.input!.split('=');
        const assetsRoot = path.join(toolchain.opts.projectRoot, 'Assets');
        // 修改文件匹配模式，排除WebGL模板目录
        const imgs = await fg([
            '**/*.png', 
            '**/*.jpg', 
            '**/*.tga',
            '!**/WebGLTemplates/**' // 新增排除规则
        ], { 
            cwd: assetsRoot 
        });

        for (const img of imgs) {
            if (img.includes('@')) continue;
            const file = path.join(assetsRoot, img);
            const metaFile = file + '.meta';
            const meta = await UnityHelper.loadMeta<Unity.Meta.Texture>(metaFile);
            if (meta.TextureImporter == null) {
                console.warn('no texture importer for:', img);
                continue;
            }
            const ps = meta.TextureImporter.platformSettings.find(ps => ps.buildTarget === target);
            if (ps == null) {
                console.warn('no platform settings for:', target, img);
                continue;
            }
            if (ps.textureFormat !== Number(format)) {
                console.error('Format mismatch:', 
                    `Platform: ${target}`, 
                    `File: ${img}`, 
                    `Current: ${ps.textureFormat}`, 
                    `Expected: ${format}`);
            }
        }
    }
}